import { useInitialState } from '@/hooks'
import { Button, List, DatePicker, NavBar, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'

import styles from './index.module.scss'
import dayjs from 'dayjs'

// import { useEffect } from 'react'
// import { useDispatch, useSelector } from 'react-redux'
import { getUserProfile, updateUserProfile } from '@/store/actions/profile'
// import { RootState } from '@/types/store'

// 修改子组件
import { Popup } from 'antd-mobile'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import { useRef, useState } from 'react'

import { useDispatch } from 'react-redux'
import { uploadPhoto } from '@/api/profile'
import { useHistory } from 'react-router-dom'
import { logout } from '@/store/actions/login'

const Item = List.Item
type InputPopup = {
  type: '' | 'name' | 'intro' | 'birthday'
  value: string
  visible: boolean
}
type ListPopup = {
  type: '' | 'gender' | 'photo'
  visible: boolean
}

const ProfileEdit = () => {
  // 普通写法
  // const dispatch = useDispatch()
  // const { userProfile } = useSelector((state: RootState) => state.profile)
  // const { photo, name, intro, gender, birthday } = userProfile
  // useEffect(() => {
  //   dispatch(getUserProfile())
  // }, [dispatch])
  // 封装复用写法
  const { userProfile } = useInitialState(getUserProfile, 'profile')
  const { photo, name, intro, gender, birthday } = userProfile

  // 1. 控制修改昵称和简介
  // const [inputVisible, setInputVisible] = useState(false)
  const [inputPopup, setInputPopup] = useState<InputPopup>({
    type: '',
    value: '',
    visible: false,
  })

  // const onInputShow = (b: boolean) => {
  //   setInputVisible(b)
  // }

  const onInputShow = (
    type: InputPopup['type'],
    value: string,
    visible: boolean
  ) => {
    setInputPopup({
      type,
      value,
      visible,
    })
  }
  const dispatch = useDispatch()
  const onUpdateName = async (type: InputPopup['type'], value: string) => {
    // console.log('父组件拿到修改后的昵称：', value)
    // if (inputPopup.type === 'name') {
    //   await dispatch(updateUserProfile({ name:value }))
    // } else {
    //   await dispatch(updateUserProfile({ intro: value }))
    // }
    await dispatch(updateUserProfile({ [type]: value }))
    Toast.show({
      content: '更新成功',
      duration: 1000,
    })

    onInputShow('', '', false)
  }

  // 2. 修改性别和头像
  const [listPopup, setListPopup] = useState<ListPopup>({
    type: '',
    visible: false,
  })

  const onGenderShow = (type: ListPopup['type'], visible: boolean) => {
    setListPopup({
      type,
      visible,
    })
  }

  // 上传隐藏域
  const fileRef = useRef<HTMLInputElement>(null)
  // 获取file对象
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files?.length) {
      return
    }
    const formData = new FormData()
    formData.append('photo', e.target.files[0])
    console.log(formData.get('photo'))
    // 上传头像
    const { data } = await uploadPhoto(formData)
    dispatch(updateUserProfile({ photo: data.photo }))
  }
  const onUpdateProfile = async (
    type: ListPopup['type'],
    value: string | number
  ) => {
    // ...
    if (type === 'photo') {
      fileRef.current!.click()
    } else {
      await dispatch(updateUserProfile({ [type]: value }))
    }

    onGenderShow('', false)
  }

  // 3. 修改生日
  const [showBirthday, setShowBirthday] = useState(false)
  const onBirthdayShow = (show: boolean) => {
    setShowBirthday(show)
  }

  const onUpdateBirthday = (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')

    onUpdateName('birthday', birthday)
    onBirthdayShow(false)
  }

  // 4. 退出登录
  const history = useHistory()
  const onLogout = () => {
    // Dialog.confirm({
    //   title: '亲，确定退出吗？',
    //   confirmText: '退出',
    //   cancelText: '取消',
    //   onConfirm() {
    //     console.log('go')
    //   },
    // })
    const handler = Dialog.show({
      title: '温馨提示',
      content: '亲，你确定退出吗？',
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            onClick: () => {
              handler.close()
            },
          },
          {
            key: 'confirm',
            text: '退出',
            style: {
              // color: 'blue',
              color: 'var(--test)',
            },
            onClick: () => {
              dispatch(logout())
              handler.close()
              history.replace('/login')
            },
          },
        ],
      ],
    })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}>
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              onClick={() => onGenderShow('photo', true)}
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={photo} alt="" />
                </span>
              }
              arrow>
              头像
            </Item>
            <Item
              arrow
              extra={name}
              onClick={() => onInputShow('name', name, true)}>
              昵称
            </Item>
            <Item
              arrow
              onClick={() => onInputShow('intro', intro, true)}
              extra={
                <span className={classNames('intro', intro && 'normal')}>
                  {intro || '未填写'}
                </span>
              }>
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              onClick={() => onGenderShow('gender', true)}
              arrow
              extra={gender === 0 ? '男' : '女'}>
              性别
            </Item>
            <Item arrow extra={birthday} onClick={() => onBirthdayShow(true)}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={showBirthday}
            value={new Date(birthday)}
            onCancel={() => onBirthdayShow(false)}
            onConfirm={onUpdateBirthday}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button onClick={onLogout} className="btn">
            退出登录
          </Button>
        </div>
      </div>
      {/* 弹出层 */}
      {/* 1. 修改昵称和简介 */}
      <Popup visible={inputPopup.visible} position="right">
        <EditInput
          type={inputPopup.type}
          value={inputPopup.value}
          onClose={() => onInputShow('', '', false)}
          onUpdateName={onUpdateName}
        />
      </Popup>
      {/* 修改性别和头像 */}
      <Popup visible={listPopup.visible}>
        <EditList
          type={listPopup.type}
          onUpdateProfile={onUpdateProfile}
          onClose={() => onGenderShow('', false)}
        />
      </Popup>
      {/* 上传隐藏域 */}
      <input type="file" hidden onChange={onChangePhoto} ref={fileRef} />
    </div>
  )
}

export default ProfileEdit
